# -*- coding: utf-8 -*-
# data : 2020/4/20
from channels.generic.websocket import AsyncWebsocketConsumer
import json
from channels.http import AsgiRequest, AsgiHandler
from django.utils.decorators import method_decorator


class ServiceConsumer(AsyncWebsocketConsumer):

	async def connect(self, *args, **kwargs):
		print('***********open************')
		user = self.scope["user"]
		user_id = ""
		# todo 如果用户没有登陆 可以直接关闭连接
		# if not user.id:
		# 	await self.close()
		self.role_pk = self.scope['url_route']['kwargs']['role_pk']
		self.room_group_name = 'role_{}'.format(self.role_pk)
		await self.channel_layer.group_add(
			self.room_group_name,
			self.channel_name
		)

		await self.channel_layer.group_add(
			"all_role",
			self.channel_name
		)

		await self.accept()
		await self.send(text_data=json.dumps({
			'text': "success"
		}))

	# # Receive message from room group
	async def user_message(self, event):
		# todo: get real user from service detection api
		print(self.scope["user"])
		message = event['text']

		await self.send(text_data=json.dumps({
			'text': message
		}))

	async def receive(self, text_data=None, bytes_data=None):
		"""接收私信"""

		if isinstance(text_data, str):
			await self.send(text_data=text_data)
		else:
			await self.send(text_data=json.dumps(text_data))

	async def disconnect(self, code):
		"""离开聊天组"""
		await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
		await self.channel_layer.group_discard("all_role", self.channel_name)

	async def send_message(self, event):
		message = event['text']
		print("send_message_server", message)
		await self.send(text_data=json.dumps(message))
